package com.shaoshaohuo.app.ui.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.FramOrderRemarkAdapter;
import com.shaoshaohuo.app.adapter.FramOrderStaticAdapter;
import com.shaoshaohuo.app.entity.FarmOneRemark;
import com.shaoshaohuo.app.entity.FramOrderStaticEntity;
import com.shaoshaohuo.app.entity.OrderShopInfoEntity;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.ui.ItemOrderDetails;
import com.shaoshaohuo.app.utils.Okhttputils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;


public class FarmOrderStaticFragment extends Fragment implements TextWatcher, FramOrderStaticAdapter.FarmCallBack {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;

    private View view;
    private EditText farm_order_static_editText;
    private ListView farm_order_static_listView;
    private List<FramOrderStaticEntity.DataBean> data;
    private FramOrderStaticAdapter framOrderStaticAdapter;
    private static final String WAIT_SURE = "1";//待确认
    private static final String FINISED = "2";//已完成
    private static final String ALL = "3";//全部
    //    private static final String REMARK = "1";
    private LinearLayout farm_order_static_linearLayout;

    //评价
    private FramOrderRemarkAdapter framOrderRemarkAdapter;
    private List<FarmOneRemark.DataBean> remark_data;
    private TextView farm_order_static_find_textView;
    private String intput_string;
    //搜索
    private List<FramOrderStaticEntity.DataBean> seacrh_data;
    private FarmOrderStaticFragment.Mybrocatrecier mybrocatrecier;
    private List<FramOrderStaticEntity.DataBean> mData;

    public FarmOrderStaticFragment() {
    }

    private Activity activity;

    public static FarmOrderStaticFragment newInstance(String param1, String param2) {
        FarmOrderStaticFragment fragment = new FarmOrderStaticFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString("type");
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        Log.e("跳过来的数据", mParam1);
        activity = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_farm_order_static, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        getData();
        decideData();
        bindAdapter();
        initListener();
    }

    private void getData() {
        if (mParam1.equals("全部")) {
            farm_order_static_linearLayout.setVisibility(View.GONE);
        } else if (mParam1.equals("待确认")) {
            farm_order_static_linearLayout.setVisibility(View.VISIBLE);
        } else if (mParam1.equals("已完成")) {
            farm_order_static_linearLayout.setVisibility(View.GONE);
        } else if (mParam1.equals("评价")) {
            farm_order_static_linearLayout.setVisibility(View.GONE);

        }
    }

    private void getRemark() {
        ShopHttpConfig.FramGetOneRemark(getActivity(), new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {
                Log.e("失败", "失败");
            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                Log.e("成功", "成功");
                final FarmOneRemark farmOneRemark = (FarmOneRemark) o;
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        framOrderRemarkAdapter.refreshData(farmOneRemark.getData());
                    }
                });
            }
        }, FarmOneRemark.class);
    }

    //搜索订单数据
    private void searchData() {
        seacrh_data = new ArrayList<>();
        if (mData.size() != 0 || mData != null) {
            String string = farm_order_static_editText.getText().toString().trim();
            for (int i = 0; i < mData.size(); i++) {
                String phone = mData.get(i).getPhone();
                if (string.equals(phone)) {
                    seacrh_data.add(mData.get(i));
                }
                Log.e("phone", mData.get(i) + "");
            }
            if (seacrh_data.size() == 0) {
                Toast.makeText(getActivity(), "没有数据", Toast.LENGTH_SHORT).show();
            }
            if (seacrh_data.size() != 0) {
                framOrderStaticAdapter.refreshData(seacrh_data);
            }
        } else {
            Toast.makeText(getActivity(), "没有数据", Toast.LENGTH_SHORT).show();
        }
    }

    private String decideData() {
        if (mParam1.equals("评价")) {
            getRemark();
        } else {
            requestData();
        }
        return "";
    }

    private String decideType() {
        if (mParam1.equals("全部")) {
            return ALL;
        } else if (mParam1.equals("待确认")) {
            return WAIT_SURE;
        } else if (mParam1.equals("已完成")) {
            return FINISED;
        }
        return ALL;
    }

    private void requestData() {
        String type = decideType();
        ShopHttpConfig.FarmAllOrder(getActivity(), type, new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {
                Log.e("请求", "失败");
            }

            @Override
            public void suseff(Call call, Response response, final Object o) {
                Log.e("请求", "成功");
                final FramOrderStaticEntity orderentity = (FramOrderStaticEntity) o;
                data = orderentity.getData();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        framOrderStaticAdapter.refreshData(orderentity.getData());
                    }
                });
            }
        }, FramOrderStaticEntity.class);
    }

    private void bindAdapter() {
        if (mParam1.equals("全部") || mParam1.equals("待确认") || mParam1.equals("已完成")) {
            farm_order_static_listView.setAdapter(framOrderStaticAdapter);
        } else if (mParam1.equals("评价")) {
            farm_order_static_listView.setAdapter(framOrderRemarkAdapter);
        }
    }

    private void initListener() {
//        farm_order_static_editText.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                farm_order_static_editText.setCursorVisible(true);
//                return false;
//            }
//        });
//        farm_order_static_editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                    searchData();
//                    return true;
//                }
//                return false;
//            }
//        });
        farm_order_static_editText.addTextChangedListener(this);
        farm_order_static_find_textView.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                mData = framOrderStaticAdapter.getData();
                if (mData != null && mData.size() != 0 && farm_order_static_editText.getText().toString().trim().length() != 0 && farm_order_static_editText.getText().toString().trim() != null) {
                    Log.e("ssss", FarmOrderStaticFragment.this.data.size() + "" + farm_order_static_editText.getText().toString().trim());
                    searchData();
                } else {
                    Toast.makeText(getActivity(), "输入不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        farm_order_static_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                OrderShopInfoEntity.DataBean dataBean = new OrderShopInfoEntity.DataBean();
                List<FramOrderStaticEntity.DataBean> data1 = framOrderStaticAdapter.getData();
                Log.e("getName", data1.get(position).getName() + "==" + data1.get(position).getOrderid() + "==" + data1.get(position).getImg() + "==" + data1.get(position).getTime());
                dataBean.setName(data1.get(position).getName());
                dataBean.setOrderid(data1.get(position).getOrderid());
                String status = data1.get(position).getStatus();
                dataBean.setImg(data1.get(position).getImg());
                dataBean.setFin_money(data1.get(position).getPrice());
                dataBean.setBuy_num("1");
                dataBean.setPay_time(data1.get(position).getTime());
                intent.setClass(getActivity(), new ItemOrderDetails().newInstance(intent, dataBean, status, "2", "1").getClass());
//                intent.putExtra("intent_data", dataBean);
//                intent.putExtra("type", "2");
//                intent.putExtra("status", status);
//                intent.putExtra("usertype", "1");//商户采摘
                Log.e("aaaa", dataBean.getStatus() + dataBean.getImg() + dataBean.getName() + dataBean.getPay_time() + dataBean.getOrderid());
                startActivity(intent);
            }
        });
    }

    private void initView() {
        farm_order_static_editText = (EditText) view.findViewById(R.id.farm_order_static_editText);
        farm_order_static_listView = (ListView) view.findViewById(R.id.farm_order_static_listView);
        data = new ArrayList<>();
        framOrderStaticAdapter = new FramOrderStaticAdapter(getActivity(), data, mParam1);
        farm_order_static_linearLayout = (LinearLayout) view.findViewById(R.id.farm_order_static_linearLayout);
        //评价
        remark_data = new ArrayList<>();
        framOrderRemarkAdapter = new FramOrderRemarkAdapter(getActivity(), remark_data);
        farm_order_static_find_textView = (TextView) view.findViewById(R.id.farm_order_static_find_textView);

        mybrocatrecier = new FarmOrderStaticFragment.Mybrocatrecier();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("sure");
        getActivity().registerReceiver(mybrocatrecier, intentFilter);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        intput_string = s.toString();
        if (intput_string.length() == 0 || intput_string == null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    framOrderStaticAdapter.refreshData(data);
                }
            });
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void callBackListener() {
        decideData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mybrocatrecier != null) {
            getActivity().unregisterReceiver(mybrocatrecier);
        }

    }

    class Mybrocatrecier extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("sure")) {
//                String daifukuan = (String) intent.getExtras().get("daifukuan");
                decideData();
            }
        }
    }
}
